package com.danbay.framework.web;

import com.danbay.framework.exception.CodeBusinessException;
import com.danbay.framework.web.json.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 * @author SJG
 *         2017/11/16.
 */
@ControllerAdvice
public class GlobalExceptionHandlerConfig {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResult jsonErrorHandler(HttpServletRequest req, Exception e) {
        JsonResult r = new JsonResult<>();
        r.setMessage(e.getMessage());
        if(e instanceof CodeBusinessException){
            CodeBusinessException codeBusinessException= (CodeBusinessException) e;
            r.setCode(codeBusinessException.getCode());
        }else{
            r.setCode(500);
        }
        r.setResult(false);
        return r;
    }
}
